import React, { useState, useRef } from 'react'
import { Button, Input, Card, Select, Slider, message, Space, Typography, Alert } from 'antd'
import { PlayCircleOutlined, StopOutlined, SoundOutlined } from '@ant-design/icons'
import XunfeiTTS from '../utils/xunfeiTTS'
import type { TTSConfig, TTSOptions } from '../utils/xunfeiTTS'

const { TextArea } = Input
const { Option } = Select
const { Title, Text } = Typography

interface TTSDebuggerProps {
  style?: React.CSSProperties
}

const TTSDebugger: React.FC<TTSDebuggerProps> = ({ style }) => {
  const [text, setText] = useState('你好，这是语音合成测试。')
  const [isPlaying, setIsPlaying] = useState(false)
  const [isSynthesizing, setIsSynthesizing] = useState(false)
  const [debugInfo, setDebugInfo] = useState<string[]>([])
  const [voice, setVoice] = useState('xiaoyan')
  const [speed, setSpeed] = useState(50)
  const [volume, setVolume] = useState(50)
  const [pitch, setPitch] = useState(50)
  
  const ttsRef = useRef<XunfeiTTS | null>(null)
  const audioRef = useRef<HTMLAudioElement | null>(null)

  // 初始化TTS服务
  const initTTS = () => {
    try {
      const config: TTSConfig = {
        appId: import.meta.env.VITE_XUNFEI_APP_ID || '',
        apiKey: import.meta.env.VITE_XUNFEI_API_KEY || '',
        apiSecret: import.meta.env.VITE_XUNFEI_API_SECRET || ''
      }

      addDebugInfo('🔧 TTS配置检查:')
      addDebugInfo(`- APP_ID: ${config.appId ? '已配置' : '❌ 未配置'}`)
      addDebugInfo(`- API_KEY: ${config.apiKey ? '已配置' : '❌ 未配置'}`)
      addDebugInfo(`- API_SECRET: ${config.apiSecret ? '已配置' : '❌ 未配置'}`)

      if (!config.appId || !config.apiKey || !config.apiSecret) {
        addDebugInfo('❌ TTS配置不完整，请检查环境变量')
        message.error('TTS配置不完整，请检查.env文件')
        return false
      }

      ttsRef.current = new XunfeiTTS(config)
      addDebugInfo('✅ TTS服务初始化成功')
      return true
    } catch (error) {
      addDebugInfo(`❌ TTS初始化失败: ${error}`)
      message.error('TTS初始化失败')
      return false
    }
  }

  const addDebugInfo = (info: string) => {
    setDebugInfo(prev => [...prev, `[${new Date().toLocaleTimeString()}] ${info}`])
  }

  const clearDebugInfo = () => {
    setDebugInfo([])
  }

  const testTTS = async () => {
    if (!ttsRef.current && !initTTS()) {
      return
    }

    if (!text.trim()) {
      message.warning('请输入要合成的文本')
      return
    }

    try {
      setIsSynthesizing(true)
      addDebugInfo(`🎤 开始语音合成: "${text}"`)
      addDebugInfo(`🎛️ 参数: 发音人=${voice}, 语速=${speed}, 音量=${volume}, 音调=${pitch}`)

      const options: TTSOptions = {
        voice,
        speed,
        volume,
        pitch
      }

      const audioData = await ttsRef.current!.synthesize(text, options)
      addDebugInfo(`📊 合成完成，音频数据大小: ${audioData.byteLength} 字节`)

      // 转换为WAV格式
      const wavData = ttsRef.current!.pcmToWav(audioData)
      addDebugInfo(`🔄 PCM转WAV完成，WAV数据大小: ${wavData.byteLength} 字节`)

      // 创建音频对象并播放
      const audioBlob = new Blob([wavData], { type: 'audio/wav' })
      const audioUrl = URL.createObjectURL(audioBlob)
      
      if (audioRef.current) {
        audioRef.current.src = audioUrl
        
        audioRef.current.onplay = () => {
          setIsPlaying(true)
          addDebugInfo('▶️ 音频开始播放')
        }
        
        audioRef.current.onended = () => {
          setIsPlaying(false)
          URL.revokeObjectURL(audioUrl)
          addDebugInfo('⏹️ 音频播放完成')
        }
        
        audioRef.current.onerror = (error) => {
          setIsPlaying(false)
          URL.revokeObjectURL(audioUrl)
          addDebugInfo(`❌ 音频播放失败: ${error}`)
          message.error('音频播放失败')
        }

        await audioRef.current.play()
        addDebugInfo('🔊 音频播放开始')
      }
    } catch (error) {
      addDebugInfo(`❌ 语音合成失败: ${error}`)
      message.error(`语音合成失败: ${error}`)
    } finally {
      setIsSynthesizing(false)
    }
  }

  const stopPlaying = () => {
    if (audioRef.current) {
      audioRef.current.pause()
      audioRef.current.currentTime = 0
      setIsPlaying(false)
      addDebugInfo('⏹️ 音频播放已停止')
    }
  }

  const testBrowserTTS = () => {
    if ('speechSynthesis' in window) {
      const utterance = new SpeechSynthesisUtterance(text)
      utterance.lang = 'zh-CN'
      utterance.rate = speed / 50
      utterance.volume = volume / 100
      utterance.pitch = pitch / 50

      utterance.onstart = () => {
        addDebugInfo('🔊 浏览器TTS开始播放')
      }

      utterance.onend = () => {
        addDebugInfo('⏹️ 浏览器TTS播放完成')
      }

      utterance.onerror = (error) => {
        addDebugInfo(`❌ 浏览器TTS播放失败: ${error.error}`)
      }

      speechSynthesis.speak(utterance)
      addDebugInfo('🎤 使用浏览器内置TTS播放')
    } else {
      addDebugInfo('❌ 浏览器不支持语音合成')
      message.error('浏览器不支持语音合成')
    }
  }

  return (
    <Card 
      title={
        <Space>
          <SoundOutlined />
          <span>TTS语音合成调试器</span>
        </Space>
      }
      style={{ width: 600, ...style }}
    >
      <Space direction="vertical" style={{ width: '100%' }}>
        <Alert
          message="TTS调试工具"
          description="用于测试讯飞语音合成功能，诊断语音播报问题"
          type="info"
          showIcon
        />

        <div>
          <Text strong>合成文本:</Text>
          <TextArea
            value={text}
            onChange={(e) => setText(e.target.value)}
            placeholder="请输入要合成的文本"
            rows={3}
            style={{ marginTop: 8 }}
          />
        </div>

        <div>
          <Text strong>发音人:</Text>
          <Select
            value={voice}
            onChange={setVoice}
            style={{ width: '100%', marginTop: 8 }}
          >
            <Option value="xiaoyan">小燕(女声)</Option>
            <Option value="xiaoyu">小宇(男声)</Option>
            <Option value="xiaoxin">小新(童声)</Option>
            <Option value="aisxping">艾思平(女声)</Option>
            <Option value="aisjinger">艾思婧(女声)</Option>
          </Select>
        </div>

        <div>
          <Text strong>语速: {speed}</Text>
          <Slider
            min={0}
            max={100}
            value={speed}
            onChange={setSpeed}
            style={{ marginTop: 8 }}
          />
        </div>

        <div>
          <Text strong>音量: {volume}</Text>
          <Slider
            min={0}
            max={100}
            value={volume}
            onChange={setVolume}
            style={{ marginTop: 8 }}
          />
        </div>

        <div>
          <Text strong>音调: {pitch}</Text>
          <Slider
            min={0}
            max={100}
            value={pitch}
            onChange={setPitch}
            style={{ marginTop: 8 }}
          />
        </div>

        <Space>
          <Button
            type="primary"
            icon={<PlayCircleOutlined />}
            onClick={testTTS}
            loading={isSynthesizing}
            disabled={isPlaying}
          >
            测试讯飞TTS
          </Button>
          
          <Button
            icon={<StopOutlined />}
            onClick={stopPlaying}
            disabled={!isPlaying}
          >
            停止播放
          </Button>

          <Button
            onClick={testBrowserTTS}
            disabled={isSynthesizing || isPlaying}
          >
            测试浏览器TTS
          </Button>

          <Button onClick={clearDebugInfo}>
            清空日志
          </Button>
        </Space>

        <div>
          <Title level={5}>调试信息:</Title>
          <div 
            style={{ 
              height: 200, 
              overflow: 'auto', 
              border: '1px solid #d9d9d9', 
              padding: 8,
              backgroundColor: '#fafafa',
              fontFamily: 'monospace',
              fontSize: '12px'
            }}
          >
            {debugInfo.map((info, index) => (
              <div key={index}>{info}</div>
            ))}
          </div>
        </div>
      </Space>

      <audio ref={audioRef} style={{ display: 'none' }} />
    </Card>
  )
}

export default TTSDebugger